/**
 * 设计快递单打印模板
 * 
 * @author 李静波
 */
Ext.define("PSI.Express.BillTemplateDesignForm", {
	extend : "Ext.window.Window",

	config : {
		parentForm : null,
		entity : null
	},

	/**
	 * 初始化组件
	 */
	initComponent : function() {
		var me = this;
		var entity = me.getEntity();

		Ext.apply(me, {
					title : "设计打印样式",
					modal : true,
					onEsc : Ext.emptyFn,
					width : 700,
					height : 600,
					maximized : true,
					layout : "border",
					tbar : [{
								text : "保存",
								id : "buttonSave",
								iconCls : "PSI-button-ok",
								handler : me.onOK,
								scope : me
							}, "-", {
								text : "取消",
								id : "buttonCancel",
								iconCls : "PSI-button-cancel",
								handler : function() {
									if (confirm("请确认是否取消当前操作？")) {
										me.close();
									}
								},
								scope : me
							}],
					items : [{
								region : "center",
								layout : "fit",
								items : [{
											xtype : "container",
											html : me.getLodopHtml()
										}]
							}, {
								region : "west",
								width : 300,
								layout : "border",
								border : 0,
								bodyPadding : 10,
								items : [{
									region : "north",
									layout : {
										type : "table",
										columns : 1
									},
									height : 230,
									bodyPadding : 10,
									border : 0,
									items : [{
												xtype : "hidden",
												id : "companyId",
												name : "id",
												value : entity.get("id")
											}, {
												colspan : 2,
												border : 0,
												margin : 0,
												html : "<h2>"
														+ entity.get("name")
														+ "</h2>"
											}, {
												id : "editPageTop",
												labelWidth : 100,
												labelAlign : "right",
												labelSeparator : "",
												xtype : "numberfield",
												hideTrigger : true,
												margin : 5,
												fieldLabel : "向下偏(毫米)"
											}, {
												id : "editPageLeft",
												labelWidth : 100,
												labelAlign : "right",
												labelSeparator : "",
												xtype : "numberfield",
												hideTrigger : true,
												margin : 5,
												fieldLabel : "向右偏(毫米)"
											}, {
												id : "editPageWidth",
												labelWidth : 100,
												labelAlign : "right",
												labelSeparator : "",
												xtype : "numberfield",
												hideTrigger : true,
												margin : 5,
												fieldLabel : "纸张宽度(毫米)"
											}, {
												id : "editPageHeight",
												labelWidth : 100,
												labelAlign : "right",
												labelSeparator : "",
												xtype : "numberfield",
												hideTrigger : true,
												margin : 5,
												fieldLabel : "纸张高度(毫米)"
											}, {
												id : "editPageOrient",
												xtype : "combo",
												queryMode : "local",
												editable : false,
												valueField : "id",
												labelWidth : 100,
												labelAlign : "right",
												labelSeparator : "",
												fieldLabel : "打印方向",
												margin : 5,
												store : Ext.create(
														"Ext.data.ArrayStore",
														{
															fields : ["id",
																	"text"],
															data : [
																	["1",
																			"纵向打印"],
																	["2",
																			"横向打印"]]
														}),
												value : 1
											}]
								}, {
									region : "center",
									layout : "fit",
									items : [me.getPageItemGrid()]

								}]
							}],
					listeners : {
						show : {
							fn : me.onWndShow,
							scope : me
						},
						close : {
							fn : me.onWndClose,
							scope : me
						}
					}
				});

		me.callParent(arguments);

		me.__editorList = ["editPageLeft", "editPageTop", "editPageWidth",
				"editPageHeight", "editPageOrient"];
	},

	onWindowBeforeUnload : function(e) {
		return (window.event.returnValue = e.returnValue = '确认离开当前页面？');
	},

	onWndClose : function() {
		Ext.get(window).un('beforeunload', this.onWindowBeforeUnload);
	},

	onWndShow : function() {
		Ext.get(window).on('beforeunload', this.onWindowBeforeUnload);

		var me = this;
		var el = me.getEl();
		var unitStore = me.unitStore;
		el.mask(PSI.Const.LOADING);

		var r = {
			url : PSI.Const.BASE_URL + "Home/Express/getTemplateInfoForDesign",
			params : {
				id : me.getEntity().get("id")
			},
			method : "POST",
			callback : function(options, success, response) {
				el.unmask();

				if (!success) {
					return;
				}

				var data = Ext.JSON.decode(response.responseText);

				if (!data.hasPrintData) {
					alert("还没有设置打印项，不能设计打印样式");
					me.close();
				}

				var store = me.getPageItemGrid().getStore();
				store.removeAll();
				store.add(data.items);

				var v = data.pageInfo;
				Ext.getCmp("editPageLeft").setValue(v.pageLeft);
				Ext.getCmp("editPageTop").setValue(v.pageTop);
				Ext.getCmp("editPageWidth").setValue(v.pageWidth);
				Ext.getCmp("editPageHeight").setValue(v.pageHeight);
				Ext.getCmp("editPageOrient").setValue(v.pageOrient);

				me.initPrintCmp(data);
			}
		};

		Ext.Ajax.request(r);
	},

	onOK : function() {
		var me = this;

		var el = Ext.getBody();
		el.mask("正在保存中...");
		Ext.Ajax.request({
			url : PSI.Const.BASE_URL + "Home/Express/designExpressBillTemplate",
			method : "POST",
			params : {
				jsonStr : me.getSaveData()
			},
			callback : function(options, success, response) {
				el.unmask();

				if (success) {
					var data = Ext.JSON.decode(response.responseText);
					if (data.success) {
						me.close();
						me.getParentForm().refreshTemplateInfo();
					} else {
						alert(data.msg);
					}
				}
			}
		});
	},

	onEditSpecialKey : function(field, e) {
		if (e.getKey() === e.ENTER) {
			var me = this;
			var id = field.getId();
			for (var i = 0; i < me.__editorList.length; i++) {
				var editorId = me.__editorList[i];
				if (id === editorId) {
					var edit = Ext.getCmp(me.__editorList[i + 1]);
					edit.focus();
					edit.setValue(edit.getValue());
				}
			}
		}
	},

	getSaveData : function() {
		var me = this;
		var lodop = me.getLodopCmp();

		var result = {
			companyId : Ext.getCmp("companyId").getValue(),
			pageLeft : Ext.getCmp("editPageLeft").getValue(),
			pageTop : Ext.getCmp("editPageTop").getValue(),
			pageWidth : Ext.getCmp("editPageWidth").getValue(),
			pageHeight : Ext.getCmp("editPageHeight").getValue(),
			pageOrient : Ext.getCmp("editPageOrient").getValue(),
			items : []
		};

		var store = me.getPageItemGrid().getStore();
		for (var i = 0; i < store.getCount(); i++) {
			var item = store.getAt(i);
			result.items.push({
						name : item.get("name"),
						caption : item.get("caption"),
						top : lodop.GET_VALUE("ItemTop", i + 1),
						left : lodop.GET_VALUE("ItemLeft", i + 1),
						width : lodop.GET_VALUE("ItemWidth", i + 1),
						height : lodop.GET_VALUE("ItemHeight", i + 1),
						fontSize : lodop.GET_VALUE("ItemFontSize", i + 1),
						isBold : lodop.GET_VALUE("Itembold", i + 1)
					});
		}

		return Ext.JSON.encode(result);
	},

	getPageItemGrid : function() {
		var me = this;
		if (me.__pageItemGrid) {
			return me.__pageItemGrid;
		}

		var modelName = "PSIExpressBillPageItem_EditForm";
		Ext.define(modelName, {
					extend : "Ext.data.Model",
					fields : ["id", "name", "caption"]
				});

		me.__pageItemGrid = Ext.create("Ext.grid.Panel", {
					viewConfig : {
						enableTextSelection : true
					},
					columnLines : true,
					columns : [{
								xtype : "rownumberer"
							}, {
								header : "打印项",
								dataIndex : "caption",
								menuDisabled : true,
								sortable : false,
								flex : 1
							}],
					store : Ext.create("Ext.data.Store", {
								model : modelName,
								autoLoad : false,
								data : []
							}),
					listeners : {
						itemdblclick : {
							fn : me.onEditCompany,
							scope : me
						}
					}
				});

		return me.__pageItemGrid;
	},

	getLodopCmp : function() {
		var me = this;

		if (me.LODOP) {
			return me.LODOP;
		}

		me.LODOP = getLodop(document.getElementById('LODOP_OB'), document
						.getElementById('LODOP_EM'));
		return me.LODOP;
	},

	getLodopHtml : function() {
		var html = "";
		html += '<object  id="LODOP_OB" classid="clsid:2105C259-1E0C-4534-8141-A753534CB4CA" width="100%" height="100%">';
		html += '  <param name="Caption" value="打印设计器">';
		html += '   <param name="Border" value="1">';
		html += '   <param name="Color" value="#C0C0C0">';
		html += '   <embed id="LODOP_EM" type="application/x-print-lodop" width="100%" height="100%" PLUGINSPAGE="install_lodop.exe">></embed>';
		html += '</object>';

		return html;
	},

	initPrintCmp : function(data) {
		var me = this;
		var lodop = me.getLodopCmp();

		var left = data.pageInfo.pageLeft + "mm";
		var top = data.pageInfo.pageTop + "mm";
		var width = data.pageInfo.pageWidth + "mm";
		var height = data.pageInfo.pageHeight + "mm";
		lodop.PRINT_INITA(left, top, width, height, "PSI_ExpressBill_"
						+ data.pageId);

		for (var i = 0; i < data.items.length; i++) {
			var item = data.items[i];
			lodop.ADD_PRINT_TEXT(item.top, item.left, item.width, item.height,
					item.caption);
			lodop.SET_PRINT_STYLE("FontSize", item.fontSize);
			lodop.SET_PRINT_STYLE("Bold", item.isBold);
		}

		lodop.SET_SHOW_MODE("SETUP_IN_BROWSE", 1);
		lodop.SET_SHOW_MODE("SETUP_ENABLESS", "11111111000000");// 隐藏关闭(叉)按钮
		lodop.SET_SHOW_MODE("HIDE_GROUND_LOCK", true);// 隐藏纸钉按钮
		lodop.PRINT_SETUP();
	}
});